﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MedievalGameProject
{
    public class BasicModel : DrawableGameComponent
    {
        public Model model { get; protected set; }
        public Matrix worldRotation = Matrix.Identity;
        public Matrix worldTranslation = Matrix.Identity;

        public float scale;

        public BasicModel(Game game, Model m) : base(game)
        {
            model = m;
            scale = 1;
        }

        public BasicModel(Game game, Model m, float scale) : this(game, m)
        {
            this.scale = scale;
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            Matrix world = (Matrix.CreateScale(scale) * worldRotation * worldTranslation);
            Draw(world);
            base.Draw(gameTime);
        }

        public virtual void Draw(Matrix world)
        {
            //Set transforms
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            //Loop through meshes and their effects 
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect be in mesh.Effects)
                {
                    //Set BasicEffect information
                    be.EnableDefaultLighting();
                    be.Projection = Game1.camera.projection;
                    be.View = Game1.camera.view;
                    be.World = world * mesh.ParentBone.Transform;
                }
                //Draw
                mesh.Draw();
            }
        }

        public virtual void Move(Vector3 velocity)
        {
            worldTranslation *= Matrix.CreateTranslation(velocity.X, velocity.Y, velocity.Z);
        }

        public void SetPosition(Vector3 pos)
        {
            worldTranslation = Matrix.CreateTranslation(pos.X, pos.Y, pos.Z);
        }

        public void FlipFacing()
        {
            worldRotation *= Matrix.CreateRotationY((float)Math.PI);
        }
    }
}
